/**
 * context状态树实现，使用函数式组件
 * @link react-basic/src/03-hooks/12_useContext.js
 */
import React, { useContext, useEffect, useReducer } from 'react'
import axios from 'axios'
import '../css/05_non_father_son.css'

const reducer = (prevState, action) => {
    let newState = { ...prevState }
    if (action.type === "init") {
        newState.filmList = action.value;
        return newState;
    }
    if (action.type === "detail") {
        newState.info = action.value;
        return newState;
    }
    return prevState
}

const initialState = {
    filmList: [],
    info: ""
}

var GlobalContext = React.createContext();

export default function App() {
    const [state, dispatch] = useReducer(reducer, initialState);
    useEffect(
        () => {
            axios.get("/test.json").then(res => {
                dispatch({
                    type: "init",
                    value: res.data.data.films
                })
            })
        }, []
    )
    return (
        <GlobalContext.Provider value={{
            state,
            dispatch
        }}>
            <div>
                {
                    state.filmList.map(item =>
                        <FilmItem key={item.filmId} {...item}></FilmItem>
                    )
                }
                <FilmDetail></FilmDetail>
            </div>
        </GlobalContext.Provider>
    )
}

function FilmItem(props) {
    let { name, poster, grade, synopsis } = props;
    const { dispatch } = useContext(GlobalContext)
    return (
        <div className="filmItem" onClick={() => {
            dispatch({
                type: "detail",
                value: synopsis
            })
        }}>
            <img src={poster} alt={name} />
            <h4>{name}</h4>
            <div>观众评分： {grade}</div>
        </div>
    )
}

function FilmDetail() {
    const { state } = useContext(GlobalContext)
    return (
        <div className="filmDetail">
            {state.info}
        </div>
    )
}
